<template>
  <div class="ele-body">
    <!-- 搜索表单 -->
    <div class="block-interval">
      <a-card :bordered="false">
        <a-form layout="inline" :model="where" @keydown.enter.prevent="reload">
          <a-row style="width: 100%">
            <a-col :span="21">
              <a-form-item label="代理商:">
                <a-select
                  placeholder="请选择代理商"
                  v-model:value="where.agentId"
                  style="width: 150px"
                  allow-clear>
                  <a-select-option v-for="item in agentList" :key="item.id" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
<!--                客户名称:
                <a-input style="width: 150px;margin-left: 10px;" v-model:value.trim="where.customerName" placeholder="请输入客户名称" allow-clear />-->
                报备单号:
                <a-input style="width: 150px;margin-left: 10px;" v-model:value.trim="where.code" placeholder="请输入报备单号" allow-clear />
<!--                报备起止日期
                <a-date-picker placeholder="开始日期"
                               fomat="YYYY-MM-DD"
                               valueFormat="YYYY-MM-DD"
                               style="width: 120px"
                               v-model:value="where.dataTimeStart">
                </a-date-picker>
                ~
                <a-date-picker placeholder="结束日期"
                               fomat="YYYY-MM-DD"
                               valueFormat="YYYY-MM-DD"
                               style="width: 120px"
                               v-model:value="where.dataTimeEnd">
                </a-date-picker>-->
                <a-space style="margin-left: 50px;">
                  <a-button type="primary" @click="reload">查询</a-button>
                  <a-button @click="reset">重置</a-button>
                </a-space>
              </a-form-item>
            </a-col>
            <!--导出excel-->
            <a-col :span="3">
              <a-form-item class="ele-text-center">
                <a-space>
                  <a-button @click="exportExcel" type="primary" :size="size"
                            style="background-color: rgb(254,108,17);border:rgb(254,108,17);">
                    <template #icon>
                      <DownloadOutlined />
                    </template>
                    按条件导出
                  </a-button>
                </a-space>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-card>
    </div>

    <!-- 表格 -->
    <div>
      <a-card :bordered="false">
        <ele-pro-table
          ref="table"
          row-key="id"
          :datasource="url"
          :parseData="parseData"
          :columns="columns"
          :where="where"
          :scroll="{ x: 'max-content' }"
        >
          <!-- table上边工具栏 -->
          <template #toolbar>
            <a-space>
              <a-radio-group v-model:value="where.status" button-style="solid" @change="reload" default-value="3">
                <a-radio-button value="3">已成交（{{ total1 }}条）</a-radio-button>
                <a-radio-button value="5">已出货（{{ total3 }}条）</a-radio-button>
                <a-radio-button value="4">已失效（{{ total2 }}条）</a-radio-button>
              </a-radio-group>
<!--              <div class="custom-tag2">{{ tabName }}共{{ totalRows }}条</div>-->
            </a-space>
          </template>

          <template #toolkit>
            <a-space style="float: right;margin-right: 50px;">
              <div class="custom-tag">总计：共{{ pageTotal }}个订单</div>
            </a-space>
          </template>

          <!-- table列表状态栏 -->
          <!-- 1是激活，2是禁用 -->
          <template #state="{ record }">
            <a-switch :checked="record.statusFlag === 1" @change="checked => editState(checked, record)" />
          </template>

          <!-- table操作栏按钮 -->
          <template #action="{ record }">
            <a-space>
              <a v-if="where.status === '3' && user.roleId !== '2'" @click="openSellCode(record)">出货</a>
              <a @click="openEdit(record)">详情</a>
            </a-space>
          </template>
          <!-- 等级-->
          <template #levelStart="{ record }">
            <a-rate :value="record.customerLevel" disabled />
          </template>

          <!-- 失效原因-->
          <template #invalidReason="{ record }">
              <span>
                {{
                  record.invalidReason.length > 10
                    ? `${record.invalidReason.slice(0, 10)}...`
                    : record.invalidReason
                }}
              </span>
          </template>
          <template #productName="{ record }">
            <span style="display: block;" v-for="(name, index) in formattedProductName(record.productName)" :key="index">
              {{ name }}
              <br>
            </span>
          </template>
        </ele-pro-table>
      </a-card>
    </div>
  </div>

  <!-- 编辑弹窗 -->
  <report-edit v-model:visible="showEdit" :data="current" @done="reload" />

  <!-- 出货的弹窗-->
  <a-modal :key="Math.random()"
           width="400px"
           :append-to-body="true"
           style="{z-index:1002}"
           title="出货"
           :visible="chVisible"
           @ok="chHandleOk"
           @cancel="chHandleCancel"
  > 设备序列号
    <a-input style="width: 200px;margin-left: 50px;" v-model:value="chInputText" placeholder="设备序列号" maxlength="50" />
  </a-modal>
</template>

<script>
import { onMounted, ref } from 'vue';
// 删除，感叹号，加号图标
import ReportEdit from './report-edit.vue';

import { AgentApi } from '@/api/AgentApi';
import { ReportApi } from '@/api/ReportApi';
import { utils, writeFile } from 'xlsx';
import { DashboardApi } from '@/api/DashboardApi';
import { WebUserApi } from '@/api/WebUserApi';

export default {
  name: 'region',
  components: {
    ReportEdit
  },

  setup() {

    // 加载代理商下拉数据
    const agentList = ref([]);

    async function fetchAgentList() {
      const res = await AgentApi.findList({});
      agentList.value = res.data;
    }

    // 页面初次挂载时加载下拉数据
    onMounted(async () => {
      await fetchAgentList();
    });

    return {
      agentList
    };
  },
  data() {
    return {
      // 表格数据接口
      url: '/business/api/report/findPageDone',
      user: {},
      // 表格列配置
      columns: [
        { title: '序号', key: 'index', width: 48, customRender: ({ index }) => this.$refs.table.tableIndex + index },
        { title: '代理商名称', dataIndex: 'agentName', width: 160, sorter: false },
        { title: '报备单号', dataIndex: 'code', sorter: false },
        {
          title: '客户等级',
          dataIndex: 'customerLevel',
          width: 160,
          sorter: true,
          slots: { customRender: 'levelStart' }
        },
        { title: '客户名称', dataIndex: 'customerName', width: 160, sorter: false },
        { title: '产品总数', dataIndex: 'productCount', width: 120, sorter: false },
        { title: '产品名称', dataIndex: 'productName', width: 150, sorter: false, slots: { customRender: 'productName' } },
        { title: '报备日期', dataIndex: 'createTime', width: 160, sorter: true },
        { title: '成交日期', dataIndex: 'transactionDate', width: 130, sorter: true },
        { title: '状态', dataIndex: 'statusName', sorter: false, width: 120 },
        { title: '操作', key: 'action', width: 120, align: 'center', fixed: 'right', slots: { customRender: 'action' } }
      ],
      columns1: [
        { title: '序号', key: 'index', width: 48, customRender: ({ index }) => this.$refs.table.tableIndex + index },
        { title: '代理商名称', dataIndex: 'agentName', width: 160, sorter: false },
        { title: '报备单号', dataIndex: 'code', sorter: false },
        {
          title: '客户等级',
          dataIndex: 'customerLevel',
          width: 160,
          sorter: true,
          slots: { customRender: 'levelStart' }
        },
        { title: '客户名称', dataIndex: 'customerName', width: 160, sorter: false },
        { title: '产品总数', dataIndex: 'productCount', width: 120, sorter: false },
        { title: '产品名称', dataIndex: 'productName', width: 150, sorter: false, slots: { customRender: 'productName' } },
        { title: '报备日期', dataIndex: 'createTime', width: 160, sorter: true },
        { title: '成交日期', dataIndex: 'transactionDate', width: 130, sorter: true },
        { title: '状态', dataIndex: 'statusName', sorter: false, width: 120 },
        { title: '操作', key: 'action', width: 120, align: 'center', fixed: 'right', slots: { customRender: 'action' } }
      ],
      columns2: [
        { title: '序号', key: 'index', width: 48, customRender: ({ index }) => this.$refs.table.tableIndex + index },
        { title: '代理商名称', dataIndex: 'agentName', width: 160, sorter: false },
        { title: '报备单号', dataIndex: 'code', sorter: false },
        {
          title: '客户等级',
          dataIndex: 'customerLevel',
          width: 160,
          sorter: true,
          slots: { customRender: 'levelStart' }
        },
        { title: '客户名称', dataIndex: 'customerName', width: 160, sorter: false },
        { title: '产品总数', dataIndex: 'productCount', width: 120, sorter: false },
        { title: '产品名称', dataIndex: 'productName', width: 150, sorter: false, slots: { customRender: 'productName' } },
        { title: '报备日期', dataIndex: 'createTime', width: 160, sorter: true },
        { title: '状态', dataIndex: 'statusName', sorter: false, width: 120 },
        { title: '失效来源', dataIndex: 'invalidSource', width: 130, sorter: true },
        {
          title: '失效原因', dataIndex: 'invalidReason', width: 200, sorter: false,
          slots: { customRender: 'invalidReason' }
          /*customRender: (text) => {
            // 如果文本长度超过10个字符，则显示前10个字符加省略号
            return text;
            // return text.length > 10 ? `${text.slice(0, 10)}...` : text;
          }*/
        },
        { title: '操作', key: 'action', width: 120, align: 'center', fixed: 'right', slots: { customRender: 'action' } }
      ],
      columns3: [
        { title: '序号', key: 'index', width: 48, customRender: ({ index }) => this.$refs.table.tableIndex + index },
        { title: '代理商名称', dataIndex: 'agentName', width: 160, sorter: false },
        { title: '报备单号', dataIndex: 'code', sorter: false },
        {
          title: '客户等级',
          dataIndex: 'customerLevel',
          width: 160,
          sorter: true,
          slots: { customRender: 'levelStart' }
        },
        { title: '客户名称', dataIndex: 'customerName', width: 160, sorter: false },
        { title: '产品总数', dataIndex: 'productCount', width: 120, sorter: false },
        { title: '设备序列号', dataIndex: 'sellCode', width: 120, sorter: false },
        { title: '产品名称', dataIndex: 'productName', width: 150, sorter: false, slots: { customRender: 'productName' } },
        { title: '报备日期', dataIndex: 'createTime', width: 160, sorter: true },
        { title: '成交日期', dataIndex: 'transactionDate', width: 130, sorter: true },
        { title: '状态', dataIndex: 'statusName', sorter: false, width: 120 },
        { title: '操作', key: 'action', width: 120, align: 'center', fixed: 'right', slots: { customRender: 'action' } }
      ],
      // 表格搜索条件
      where: {
        status: '3'
      },
      // 表格选中数据
      selection: [],
      // 当前编辑数据
      current: null,
      // 是否显示编辑弹窗
      showEdit: false,

      // 页面总计数
      tabName: '已成交',
      total1: 0,
      total2: 0,
      total3: 0,
      totalRows: 0,
      pageTotal: 0,

      chVisible: false, // 控制弹窗显示隐藏
      chCurrentRecord: {}, // 当前行数据
      chInputText: '', // 用户输入的文字
    };
  },
  mounted() {
    this.getUser();
  },
  methods: {
    formattedProductName(names) {
      return names.split(',').map(name => name.trim());
    },

    parseData(rawData) {
      const { data, code, message, success } = rawData;
      this.pageTotal = data.pageTotal;
      this.total1 = data.total1;
      this.total2 = data.total2;
      this.total3 = data.total3;
      this.totalRows = data.page.totalRows;
      return {
        data: data.page,
        code: code,
        message: message,
        success: success
      };
    },

    /*getFooter() {
      if (!this.where.status) {
        this.tabName = '已成交';
      } else if (this.where.status === '3') {
        this.tabName = '已成交';
      } else if (this.where.status === '4') {
        this.tabName = '已失效';
      }
      return <a-space style="display: flex;flex-direction: row-reverse;">
        <div
          style="background-color: rgb(255, 226, 194);color: rgb(231, 93, 0);padding: 5px 10px;font-family: Arial, sans-serif;display: inline-block;">
          {this.tabName}共{this.totalRows}条
        </div>
      </a-space>;
    },*/

    /**
     * 搜索按钮
     */
    reload() {

      // 设置计数名称
      if (!this.where.status) {
        this.tabName = '已成交';
      } else if (this.where.status === '3') {
        this.tabName = '已成交';
      } else if (this.where.status === '4') {
        this.tabName = '已失效';
      } else if (this.where.status === '5') {
        this.tabName = '已出货';
      }

      // 动态展示表格内容
      if (this.where.status === '3') {
        this.columns = this.columns1;
      } else if (this.where.status === '4') {
        this.columns = this.columns2;
      } else if (this.where.status === '5') {
        this.columns = this.columns3;
      }
      this.selection = [];
      this.$refs.table.reload({ page: 1 });
    },

    /**
     * 重置搜索
     */
    reset() {
      this.where = {};
      this.where.status = '3';//默认已完成
      this.$nextTick(() => {
        this.reload();
      });
    },

    /**
     * 打开编辑弹窗
     */
    openEdit(row) {
      this.current = row;
      this.showEdit = true;
    },

    chHandleOk() {
      // 提交逻辑，包含输入的文字和当前行的ID
      console.log( this.chCurrentRecord.id);
      console.log( this.chInputText);
      ReportApi.fixSellCode({
        id: this.chCurrentRecord.id,
        sellCode: this.chInputText
      }).then(result => {
        // 移除加载框
        this.loading = false;
        // 提示添加成功
        this.$message.success(result.message);
        this.reload();
        this.$emit('done');
        this.chVisible = false;
        this.chInputText = ''; // 清空输入框
      }).catch(error => {
        this.$message.error('出货失败:' + error);
      });
    },
    chHandleCancel() {
      this.chVisible = false;
      this.chInputText = ''; // 关闭弹窗时清空输入框
    },

    /**
     * 打开编辑弹窗
     */
    openSellCode(row) {
      this.chCurrentRecord = row;
      this.chVisible = true;
    },
    exportExcel() {
      this.loading = true;
      const exportWhere = {
        ...this.where,
        pageNo: 1,
        pageSize: 10000
      };

      ReportApi.findPageDone(exportWhere).then((res) => {
        let data = res.data.page.rows;

        let array = [];
        // 根据不同的tab状态显示不同的列
        if (this.where.status === '3') {// 已成交
          array = [
            [
              '代理商名称',
              '报备单号',
              '客户等级',
              '客户名称',
              '产品总数',
              '产品名称',
              '报备日期',
              '成交日期',
              '状态'
            ]
          ];
          data.forEach((d) => {
            array.push([
              d.agentName,
              d.code,
              d.customerLevel,
              d.customerName,
              d.productCount,
              d.productName,
              d.createTime,
              d.transactionDate,
              d.statusName
            ]);
          });
        } else if (this.where.status === '4') {// 已失效
          array = [
            [
              '代理商名称',
              '报备单号',
              '客户等级',
              '客户名称',
              '产品总数',
              '产品名称',
              '报备日期',
              '成交日期',
              '状态',
              '失效来源',
              '失效原因'
            ]
          ];
          data.forEach((d) => {
            array.push([
              d.agentName,
              d.code,
              d.customerLevel,
              d.customerName,
              d.productCount,
              d.productName,
              d.createTime,
              d.transactionDate,
              d.statusName,
              d.invalidSource,
              d.invalidReason
            ]);
          });
        } else {// 已出货
          array = [
            [
              '代理商名称',
              '报备单号',
              '客户等级',
              '客户名称',
              '产品总数',
              '设备序列号',
              '产品名称',
              '报备日期',
              '成交日期',
              '状态'
            ]
          ];
          data.forEach((d) => {
            array.push([
              d.agentName,
              d.code,
              d.customerLevel,
              d.customerName,
              d.productCount,
              d.sellCode,
              d.productName,
              d.createTime,
              d.transactionDate,
              d.statusName
            ]);
          });
        }
        writeFile(
          {
            SheetNames: ['报备单'],
            Sheets: {
              报备单: utils.aoa_to_sheet(array)
            }
          },
          '【' + this.tabName + '】' + '报备单.xlsx'
        );
        this.loading = false;
      }).catch(e => {
        this.loading = false;
        this.$message.error(e.message);
      });
    },

    // 获取用户信息
    async getUser() {
      const res = await DashboardApi.getUser();
      this.user = res.data;
    },

  }
};
</script>

<style scoped>
/*搜索框与表格之间的间隙*/
.block-interval {
  margin-bottom: 10px;
}

/*重写顶部搜索表单的样式*/
.ant-form-item {
  margin-bottom: 0;
}

/deep/ .ant-table-footer{
  background-color: #FFF;
}
.custom-tag {
  background-color: rgb(225, 234, 255);; /* 浅蓝色背景 */
  color: rgb(22, 64, 219); /* 深蓝色字体颜色 */
  padding: 5px 10px; /* 内边距，可以根据需要调整 */
  font-family: Arial, sans-serif; /* 字体，可按需选择 */
  display: inline-block; /* 使内联元素具有块级元素的属性，方便控制宽高和内外边距 */
}

.custom-tag2 {
  background-color: rgb(255, 226, 194);; /* 浅蓝色背景 */
  color: rgb(231, 93, 0); /* 深蓝色字体颜色 */
  padding: 5px 10px; /* 内边距，可以根据需要调整 */
  font-family: Arial, sans-serif; /* 字体，可按需选择 */
  display: inline-block; /* 使内联元素具有块级元素的属性，方便控制宽高和内外边距 */
}
/* 表格斑马样式 **/
/deep/.ant-table-tbody tr:nth-child(2n)
{
  background-color:#fafafa;
}
</style>
